<script setup lang="ts">
import { buyerInvoiceList, deleteInvoice } from "~/api/user";
import { formatDate } from "~/utils/func";

useSeoMeta({
  title: "开具发票 - 技能猴子",
  ogTitle: "开具发票 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

onMounted(() => {
  getList();
});

const options = ref([
  { value: 0, label: "未开票订单" },
  { value: 1, label: "已申请订单" },
  { value: 2, label: "已开票订单" },
]);
const form = ref({
  bill: null,
  date: "",
});

watch(form.value, () => {
  getList();
});

const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const getList = async () => {
  try {
    const params = {};
    if (form.value.bill !== null && form.value.bill !== undefined) {
      params.invoiceStatus = form.value.bill;
    }
    if (form.value.date !== null && form.value.date !== undefined && form.value.date.length === 2) {
      // 格式化日期为 YYYY-MM-DD 格式
      const formatDateOnly = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      // 开始日期：YYYY-MM-DD
      params.startTime = formatDateOnly(form.value.date[0]);
      // 结束日期：YYYY-MM-DD
      params.endTime = formatDateOnly(form.value.date[1]);
    }
    const { data } = await buyerInvoiceList({
      pageNum: pageNum.value,
      pageSize: 10,
      ...params,
    });
    console.log(data, '==8888==');

    tableData.value = data.records;
    total.value = data.total;
  } catch (e) {
    console.log(e);
  }
};
const currentChange = (page) => {
  pageNum.value = page;
  getList();
};

const orderTypeFormatter = (row) => {
  switch (row.orderType) {
    case 1:
      return "服务";
    case 2:
      return "产品";
    case 3:
      return "其他";
  }
};
// 支付类型 （1:微信 2:支付宝 3:银联 4:其他)
const payTypeFormatter = (row) => {
  const payType = Number(row.payType);
  switch (payType) {
    case 1:
      return "微信";
    case 2:
      return "支付宝";
    case 3:
      return "银联";
    case 4:
      return "其他";
    default:
      return "-";
  }
};
// 发票状态格式化函数 （0:未开票 1:已申请 2:已开票)
const invoiceStatusFormatter = (row) => {
  // 支持 status 和 bill 字段（兼容性）
  const status = Number(row.status ?? row.bill);
  switch (status) {
    case 0:
      return "未开票";
    case 1:
      return "已申请";
    case 2:
      return "已开票";
    default:
      return "-";
  }
};
// 获取发票状态值（用于判断操作按钮显示）
const getInvoiceStatus = (row) => {
  return Number(row.status ?? row.bill);
};
// 下载发票
const downloadInvoice = (row) => {

  const billUrl = row?.billUrl;
  if (billUrl && billUrl.includes("http")) {
    window.open(billUrl, "_blank");
    return;
  } else {
    const url = `/api/resource/oss/download/${billUrl}`;
    window.open(url, "_blank");
  }
};
// 删除
const activeRow = ref(null);
const del = async (row) => {
  activeRow.value = row;
  dialogShow.value = true;
};
const dialogShow = ref(false);
const confirmDel = async () => {
  if (!activeRow.value) return;
  try {
    await deleteInvoice(activeRow.value.id);
    await getList();
    ElMessage.success("删除成功");
    dialogShow.value = false;
  } catch (e) {
    console.log(e);
  }
};

const invoiceHeaderAddShow = ref(false);
const openActive = ref(null);
const open = (row) => {
  openActive.value = row;
  invoiceHeaderAddShow.value = true;
};
const addInvoiceHeaderShow = ref(false);
const addHeader = () => {
  addInvoiceHeaderShow.value = true;
};
// 开票弹窗关闭
const invoiceHeaderAddClose = (type) => {
  if (type === "add") {
    getList();
  }
  invoiceHeaderAddShow.value = false;
};
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="manage-members">
    <h4 class="page-title">开具发票</h4>
    <div class="list">
      <div class="header">
        <div class="select">
          <el-select v-model="form.bill" placeholder="全部" style="width: 132px; margin-right: 12px" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-date-picker style="width: 250px" v-model="form.date" type="daterange" unlink-panels range-separator="-"
            start-placeholder="开始时间" end-placeholder="结束时间" clearable />
        </div>
        <span @click="addHeader">+ 发票抬头</span>
      </div>
      <div class="table">
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{
          background: '#F5F7FA',
          height: '54px',
          color: '#191E28',
        }" :cell-style="{ height: '70px' }">
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
          <el-table-column label="订单编号" prop="orderSn" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column label="商品名称" prop="goodsTypeName" show-overflow-tooltip></el-table-column>
          <el-table-column label="支付方式" prop="payType" width="80" align="center"
            :formatter="(row) => payTypeFormatter(row)"></el-table-column>
          <el-table-column label="金额" prop="amount" width="100" align="right"></el-table-column>
          <el-table-column label="支付时间" prop="payTime" width="180"></el-table-column>
          <el-table-column label="开票状态" prop="status" width="100" align="center">
            <template #default="scope">
              {{ invoiceStatusFormatter(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column label="开票时间" prop="openTime" width="180">
            <template #default="scope">
              <span v-if="scope.row.openTime">{{ scope.row.openTime }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="date" width="120" align="center" fixed="right">
            <template #default="scope">
              <span type="text" class="add-invoice" v-if="getInvoiceStatus(scope.row) === 0"
                @click="open(scope.row)">开票</span>
              <span type="text" class="download-btn" v-if="getInvoiceStatus(scope.row) === 2"
                @click="downloadInvoice(scope.row)">下载</span>
              <span type="text" class="del-btn" @click="del(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination layout="prev, pager, next" :page-size="10" :total="total" @current-change="currentChange" />
      </div>
    </div>
  </div>
  <BaseFooter />
  <DialogInvoiceAdd :openActive="openActive" v-if="invoiceHeaderAddShow" @close="invoiceHeaderAddClose" />
  <DialogAddInvoiceHeader v-if="addInvoiceHeaderShow" @closeDialog="addInvoiceHeaderShow = false" />
  <DialogConfirmDialog v-if="dialogShow" content="确认删除该账单？" confirmText="删除" title="提示" @close="dialogShow = false"
    @confirm="confirmDel" />
</template>

<style scoped lang="scss">
.manage-members {
  padding-top: 80px;
  width: 1200px;
  margin: 0 auto;
  padding-bottom: 36px;
}

.page-title {
  color: #191e28;
  font-size: 20px;
  padding-top: 32px;
  padding-bottom: 16px;
}

.list {
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px 24px;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;

    .select {
      flex: 1;
    }

    span {
      color: #019a81;
      font-weight: bold;
      cursor: pointer;
    }
  }

  .table {
    margin-top: 20px;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    overflow: hidden;
  }

  .del-btn {
    color: #ff4f4f;
    cursor: pointer;
    margin-left: 8px;
  }

  .add-invoice {
    color: #1dbf73;
    cursor: pointer;
    margin-right: 8px;
  }

  .download-btn {
    color: #019a81;
    cursor: pointer;
    margin-right: 8px;
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
}
</style>

<style>
.manage-members .el-select__wrapper {
  min-height: 40px;
  border-radius: 8px;
}

.manage-members .el-date-editor.el-input,
.manage-members .el-date-editor.el-input__wrapper {
  min-height: 40px;
  border-radius: 8px;
}
</style>
